package com.ruoyi.framework.handler;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SaTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @author Song
 * @date 2024/9/4 16:08
 * @description
 */
@Component
@Slf4j
public class MybatisHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Long userId = SaTokenUtils.getUserId();
            if (userId == null) {
                return;
            }
            if (BeanUtil.isNotEmpty(metaObject)){
                //获取创建人
                Object createBy = getFieldValByName("createBy", metaObject);
                if (BeanUtil.isEmpty(createBy)){
                    setFieldValByName("createBy",userId.toString(),metaObject);
                }
            }
        }catch (Exception e){
            log.info("自动填充获取信息失败:{}",e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            Long userId = SaTokenUtils.getUserId();
            if (userId == null) {
                return;
            }
            if (BeanUtil.isNotEmpty(metaObject)){
                //获取创建人
                Object updateBy = getFieldValByName("updateBy", metaObject);
                if (BeanUtil.isEmpty(updateBy)){
                    setFieldValByName("updateBy",userId.toString(),metaObject);
                }
            }
        }catch (Exception e){
            log.info("自动填充获取信息失败:{}",e.getMessage());
        }
    }
}
